var fs = require('fs');
var express = require('express');
//1.创建一个路由容器
var router = express.Router();
var student = require('./student')
//2.把方法放到路由容器里
router.get('/', (req, res) => {
    student.find((err, data) => {
        if (err) return res.status(500).send("服务器错误");
        res.render('index.html', {
            students: data
        })
    })
})
router.get('/students', (req, res) => {
    fs.readFile('./da.json', 'utf8', (err, data) => {
        if (err) return res.status(500).send("服务器错误");
        res.render('index.html', {
            students: JSON.parse(data).students
        })
    })
})
router.get('/students/new', (req, res) => {
    fs.readFile('./da.json', 'utf8', (err, data) => {
        if (err) return res.status(500).send("服务器错误");
        res.render('new.html', {
            students: JSON.parse(data).students
        })
    })
})
router.post('/students/new', (req, res) => {
    //console.log(req.body);
    var parmes = req.body;
    //console.log(parmes);
    student.save(parmes, (err) => {
        if (err) {
            console.log("保存成功")
            res.redirect('/')
        } else {
            console.log('保存失败')
            res.redirect("/students/new")
        }
    })
})
router.get('/students/edit', (req, res) => {
    student.findById(req.query.id, (err, student) => {
        if (err) return res.status(500).send("服务器错误");
        res.render('edit.html', {
            student: student
        })
    })
})
router.get('/students/edit', (req, res) => {
    student.findById(req.query.id, (err, student) => {
        if (err) return res.status(500).send("服务器错误");
        res.render('edit.html', {
            student: student
        })
    })
})
router.post('/students/edit', (req, res) => {
    //console.log(req.body);
    //console.log(parmes);
    student.updateById(req.body, (err) => {
        if (err) {
            console.log("删除成功")
        } else {
            console.log('删除失败')
        }
        res.redirect("/students")
    })
})
router.get('/students/delete', (req, res) => {
    student.delete(req.query.id, (err) => {
        if (err) {
            console.log("删除成功")
        } else {
            console.log('删除失败')
        }
        res.redirect("/students")
    })
})
//3.把router导出
module.exports = router;